package net.feling.mcloud.activity;

import android.app.*;
import android.content.*;
import android.os.IBinder;
import android.util.Log;
import android.view.*;
import android.widget.Toast;
import net.feling.mcloud.utils.Config;
import net.feling.mcloud.R;
import net.feling.mcloud.connection.ConnectService;
import net.feling.mcloud.entity.Message;
import net.feling.mcloud.entity.User;
import net.feling.mcloud.fragment.DistributeFragment;
import net.feling.mcloud.fragment.SignupFragment;
import net.feling.mcloud.utils.DeviceUtil;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import org.apache.mina.core.session.IoSession;

import java.io.Serializable;

public class MainActivity extends Activity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks, ServiceConnection {

    private static final String TAG = "MainActivity";
    public static Config config;
    private boolean exit = false;
    private static boolean firstOncreate = true;
    private IoSession ioSession = null;
    private ConnectService.MyBinder binder;
    private User user;
   // private Context context;
    /**
     * Fragment managing the behaviors, interactions and presentation of the
     * navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in
     * {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    /**
     * fragments
     */
    private static View signupView, taskDistributeView , last;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //context = this;
        config = (Config) getApplication();

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
        Log.d("生命周期", "onCreate");
        user = new User();
        //user.setDiviceCPUFreq();
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService(new Intent(this, ConnectService.class), this, Context.BIND_AUTO_CREATE);
        Log.d("生命周期", "onStart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Main", "MainActivity----onDestroy");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.container,
                PlaceholderFragment.newInstance(position + 1)).commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.section_cache);
                if (ioSession != null) {
                    Message message = new Message();
                    message.setType("".getClass().getSimpleName());
                    message.setSender(DeviceUtil.getLocalMacAddress());
                    message.setContent("Say Hello!");
                    sendMessage(message);
                } else {
                    Toast.makeText(this, "session问题...", Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                mTitle = getString(R.string.section_distribute);
                break;
            case 3:
                mTitle = getString(R.string.section_uninstall);
                break;
            case 4:
                mTitle = getString(R.string.section_signup);
                break;
            case 5:
                exit = true;
                onBackPressed();
                break;
        }
    }

    public void sendMessage(Serializable objects) {
        binder.getService().sendPackage(objects);
    }

    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP + ActionBar.DISPLAY_SHOW_TITLE);
        actionBar.setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d("session", "bind连上了");
        this.binder = (ConnectService.MyBinder) service;
        this.ioSession = binder.getServiceSession();
        if (ioSession == null) {
            Toast.makeText(this, "session为null...", Toast.LENGTH_SHORT).show();
        } else {

            Log.d("session in onServiceConnected", ioSession.hashCode() + " ");
        }
    }


    @Override
    public void onServiceDisconnected(ComponentName name) {
    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (firstOncreate) {
                firstOncreate = false;
                signupView = inflater.inflate(R.layout.fragment_signup, container, false);
                new SignupFragment(getActivity(), signupView).enable();
                taskDistributeView = inflater.inflate(R.layout.fragment_distribute, container, false);
                new DistributeFragment(getActivity(), taskDistributeView).enable();
            }
            switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
                case 1:
                    last = signupView;
                    return signupView;
                case 2:
                    last = taskDistributeView;
                    return taskDistributeView;
                case 3:
                    last = signupView;
                    return signupView;
                case 4:
                    last = signupView;
                    return signupView;
                default:
                    return last;
            }
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

    @Override
    public void onBackPressed() {

      /*  Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);*/
        //startActivity(intent);
        if (exit) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("提示");
            dialog.setMessage("确定与服务器断开连接？");
            dialog.setCancelable(false);
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    unbindService(MainActivity.this);
                    stopService(new Intent(MainActivity.this, ConnectService.class));
                    finish();
                }
            });
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            dialog.show();
        }
    }

}
